namespace Stee.CAP8.Communication.GrpcInterface
{
    using System;
    using global::Grpc.Core;
    using global::Grpc.Net.ClientFactory;
    using Microsoft.Extensions.DependencyInjection;
    public static class Cap8GrpcClientFactory
    {
        /// <summary>
        /// Create the Grpc Client instance according to the specified client type
        /// </summary>
        /// <typeparam name="T">Grpc Client Type</typeparam>
        /// <param name="provider">Service Provider</param>
        /// <returns>The instance of Grpc Client</returns>
        public static T GetClient<T>(this IServiceProvider provider) where T : ClientBase
        {
            if (provider == null)
            {
                throw new Cap8GrpcException("The service provider is null");
            }

            var factoryClient = provider.GetRequiredService<GrpcClientFactory>();
            if (factoryClient == null)
            {
                throw new Cap8GrpcException("Can not get GrpcClient factory instance from container");
            }
            else
            {
                return factoryClient.CreateClient<T>(typeof(T).Name);
            }
        }
    }
}
